<template>
    <div class="header_container">
		<div class="top-head">
            <el-dropdown @command="handleCommand" trigger="click" class="navdash">
                <span class="el-dropdown-link" >
                    <!-- <em v-if="IsSystemAdmin!=1"><br/>{{nowCompany}}</em> -->
                    <span class="logInfo">
                        {{nowCompany}}
                        <i class="iconfont icon-touxiang-kong"></i>
                        {{userName}}
                        <!--<i class="el-icon-caret-bottom el-icon&#45;&#45;right"></i>-->
                    </span>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <!--<el-dropdown-item  command="changePW" divided style="border-top:0">修改密码</el-dropdown-item>-->
                    <el-dropdown-item  command="singout" divided>{{$t('message.logout')}}</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            <el-select v-model="curLanguage" placeholder=" " class="checkLanguage" @change="setLanguage">
                <el-option v-for="item in languageOptions" :key="item.CultureCode" :label="item.CultureName" :value="item.CultureCode"></el-option>
            </el-select>
        </div>
        <el-dialog class="changePW" title="修改密码" :visible.sync="dialogVisible" width="570px">
            <el-form :label-width="labelW" :model="ruleForm" ref="ruleForm" :rules="rules">
                <el-form-item label="新密码" prop="newPassword">
                    <el-input clearable type="password" v-model="ruleForm.newPassword"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="newPasswordagain">
                    <el-input clearable type="password" v-model="ruleForm.newPasswordagain"></el-input>
                </el-form-item>
                <el-alert title="第一次登录" type="error" style="width:98%;margin-left:2%"> </el-alert>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-tooltip class="item" effect="dark" :content="$t('message.cancel')" placement="top">
                    <el-button @click="cancel" icon="iconfont icon-guanbi-wukuang"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" :content="$t('message.modify')" placement="top">
                    <el-button type="primary" icon="iconfont icon-gou-wukuang" @click="modify('ruleForm')"></el-button>
                </el-tooltip>
            </span>
        </el-dialog>
        <div class="breadcrumb">
            <el-breadcrumb separator="/">
                <!-- <el-breadcrumb-item :to="{ path: '/manage' }">首页</el-breadcrumb-item> -->
                <el-breadcrumb-item v-for="(item, index) in $route.meta" separator="/"   v-bind:key="index">{{$t('message.'+item)}}</el-breadcrumb-item>
            </el-breadcrumb>
            <!-- <div class="backbtn">
                <el-button type="primary" icon="el-icon-arrow-left" v-if="isShowBack" @click="goback()">返回</el-button>
            </div> -->
        </div>
    </div>
</template>

<script>
    // import { signout, login, ModPassword, getlanguage } from "@/api/getData";
    import { baseImgPath } from "@/config/env";
    import { mapActions, mapState } from "vuex";
    import { getStore, setStore, getLocal, setLocal } from "../config/mUtils";
    import { Loading } from "element-ui";
    import en from '../i18n/langs/en';
    import cn from '../i18n/langs/cn';
    export default {
        data() {
            let validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error("请再次输入密码"));
                } else if (value !== this.ruleForm.newPassword) {
                    callback(new Error("两次输入的密码不一致"));
                } else {
                    callback();
                }
            };
            return {
                baseImgPath,
                userName: "",
                companydata: [],
                nowCompanyCode: "",
                nowCompany: "",
                isShowBack: true,
                dialogVisible: false,
                labelW: 0 + 'px',
                ruleForm: {
                    newPassword:"",
                    newPasswordagain:""
                },
                rules: {
                    newPassword: [{ required: true, message: "请输入新密码", trigger: "change" },
                        { required: true, message: "密码格式不正确", pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{6,20}$/, trigger: 'blur' }],
                    newPasswordagain: [{required: true, validator: validatePass2, trigger: 'change' }],
                },
                IsSystemAdmin:getStore('IKYCZ'),
                languageOptions: [
                    {
                        CultureName: this.$t('message.chinese'),
                        CultureCode: 'zh_CN'
                    }, {
                        CultureName: this.$t('message.english'),
                        CultureCode: 'en_US'
                    }
                ],
                isShowMenu:getStore('isShowMenu'),
                curLanguage: getLocal('language')
            };
        },
        computed: {
            ...mapState(["adminInfo"])
        },
        watch:{
            cn:function(){
                //this.getLanguageResource();
            },
            en:function(){
                // this.getLanguageResource();
            },
            deep:true
        },
        created() {
            // this.getLanguageResource();
            this.resetLabelWidth();
            // this.languageList();
            if (!this.adminInfo.id) {
                this.getAdminData();
                this.userName = getStore("Name");
                this.nowCompanyCode = getStore("CompanyCode");
                this.nowCompany = 'Fresenius Netcare Region';
                let hometPath ='/' + getStore('homePage');
                if( hometPath === this.$route.path) {
                    this.isShowBack=false;
                }
            }
        },
        mounted() {
            this.getMenuStatus(this.isShowMenu);
            $(function () {
                $(".el-dialog").draggable({ handle: ".el-dialog__header" }); //使用jqueryui中的拖拽实现模态框的拖动
            });
        },
        methods: {
            ...mapActions(["getAdminData"]),
            resetLabelWidth() {
                if (getLocal('language') == 'en_US') {
                    this.labelW = 160+'px';
                } else {
                    this.labelW = 85+'px';
                }
            },
            async languageList() {
                // debugger;
                const crs = await getlanguage({});
                if (crs.Flag) {
                    this.languageOptions = crs.Result;
                }
            },
            getMenuStatus(isShowMenu) {
                if (isShowMenu === 'true' || isShowMenu === null){
                    // document.getElementsByClassName('kpi-container')[0].style.marginLeft = '0'
                    document.getElementsByClassName('breadcrumb')[0].style.left = '200px';
                    document.getElementsByClassName('menu-btn')[0].style.left = '225px';
                    document.getElementsByClassName('el-aside')[0].style.maxWidth = '200px';
                } else {
                    // document.getElementsByClassName('kpi-container')[0].style.marginLeft = '200px';
                    document.getElementsByClassName('breadcrumb')[0].style.left = '44px';
                    document.getElementsByClassName('menu-btn')[0].style.left = '60px';
                    document.getElementsByClassName('el-main')[0].style.marginLeft = '44px';
                    document.getElementsByClassName('top-head')[0].style.marginLeft = '44px';
                    document.getElementsByClassName('el-dropdown')[0].style.marginRight = '20px';
                    document.getElementsByClassName('el-aside')[0].style.maxWidth = '44px';
                }
            },
            async handleCommand(command) {
                if (command === "singout") {
                    sessionStorage.removeItem("token");
                    this.$message({
                        type: "success",
                        message: this.$t('message.logoutSuccess')
                    });
                    this.$router.push("/");
                } else if (command === "changePW") {
                    this.dialogVisible=true;
                } else {
                    sessionStorage.removeItem("token");
                    let userName = sessionStorage.getItem("LoginName");
                    let password = sessionStorage.getItem("password");
                    sessionStorage.setItem("CompanyCode", command);
                    const res = await login({
                        parm: "grant_type=password&username=" +
                            userName +
                            "&password=" +
                            password,
                        url: command
                    });
                    if (res.access_token) {
                        setStore("token", res.access_token);
                        setStore("LoginName", res.LoginName);
                        setStore("UserName", res.UserName);
                        setStore("UserPhone", res.UserPhone);
                        setStore("CompanyCode", res.CompanyCode);
                        Loading.service({ fullscreen: true });
                        this.$router.go(0);
                        //this.$router.push('manage')
                    } else {
                        this.$message({
                            type: "error",
                            message: res.message
                        });
                    }
                }
            },
            modify(formname) {
                this.$refs[formname].validate((valid) => {
                    if (valid) {
                        this.dialogVisible = false;
                        this.changePwd(formname);
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            setLanguage() {
                setLocal('language', this.curLanguage);
                if (getLocal('language') === 'zh_CN') {
                    this.$i18n.locale = "cn";
                } else if (getLocal('language') === 'en_US') {
                    this.$i18n.locale = "en";
                } else {
                    this.$i18n.locale = "cn";
                }
                this.$emit("changeLan");
            },
            async changePwd(formname) {
                const res = await ModPassword({
                    userId:sessionStorage.getItem("Id"),
                    password:this.ruleForm.newPassword
                });
                if (res.Flag) {
                    this.$message({
                        type: "success",
                        message: "密码修改成功"
                    });
                    this.$nextTick(function () {
                        this.$refs[formname].resetFields();
                    });
                }
            },
            cancel() {
                this.dialogVisible = false;
                this.$nextTick(function () {
                    this.$refs[formname].resetFields();
                });
            },
            goback() {
                this.$router.go(-1);
            }
        }
    };
</script>
